let tooltipEl = null

function ensureTooltip() {
  if (tooltipEl) return tooltipEl
  tooltipEl = document.createElement('div')
  tooltipEl.setAttribute('data-tooltip', 'true')
  const style = tooltipEl.style
  style.position = 'fixed'
  style.zIndex = '9999'
  style.pointerEvents = 'none'
  style.background = 'rgba(0,0,0,0.75)'
  style.color = '#fff'
  style.padding = '6px 8px'
  style.borderRadius = '4px'
  style.fontSize = '12px'
  style.lineHeight = '1.4'
  style.boxShadow = '0 2px 8px rgba(0,0,0,0.2)'
  style.whiteSpace = 'nowrap'
  style.opacity = '0'
  style.transition = 'opacity 80ms ease'
  style.left = '-9999px'
  style.top = '-9999px'
  document.body.appendChild(tooltipEl)
  return tooltipEl
}

export function showTooltip(text, evtOrPos) {
  const el = ensureTooltip()
  el.textContent = text || ''
  el.style.opacity = '1'
  moveTooltip(evtOrPos)
}

export function moveTooltip(evtOrPos) {
  const el = ensureTooltip()
  let x = 0
  let y = 0
  if (evtOrPos && typeof evtOrPos === 'object') {
    if ('clientX' in evtOrPos) {
      x = evtOrPos.clientX
      y = evtOrPos.clientY
    } else {
      x = evtOrPos.x || 0
      y = evtOrPos.y || 0
    }
  }
  const pad = 12
  let left = x + pad
  let top = y + pad
  // 防止越界
  const width = el.offsetWidth
  const height = el.offsetHeight
  const vw = window.innerWidth
  const vh = window.innerHeight
  if (left + width + 8 > vw) left = x - width - pad
  if (top + height + 8 > vh) top = y - height - pad
  el.style.left = `${left}px`
  el.style.top = `${top}px`
}

export function hideTooltip() {
  if (!tooltipEl) return
  tooltipEl.style.opacity = '0'
  tooltipEl.style.left = '-9999px'
  tooltipEl.style.top = '-9999px'
}